<template>
  <div id="search_content">
    <form id="editForm">

    </form>
  </div>
</template>
<script>
  import {API_ROOT} from '../../config'
  import datePicker from './datePicker.vue';
  import dSpin from '../../components/common/Spin.vue'
  require("../../assets/js/plugins/jqGrid/css/ui.jqgrid.css"); //表格核心组件样式
  require("../../assets/js/plugins/jqGrid/jquery.jqGrid.src.js"); //表格核心组件
  require("../../assets/js/plugins/jqGrid/grid.locale-en.js"); //表格语言包

  //树组件
  require("../../assets/js/plugins/zTree/zTreeStyle/zTreeStyle.css"); //ztree  css
  require("../../assets/js/plugins/zTree/jquery.ztree.all.min.js"); //ztree
  require("../../assets/js/plugins/jquery.validator/local/en_EN.js");
  require("../../assets/js/plugins/jquery.validator/jquery.validator.css");

    export default{
      components:{
        datePicker,
        dSpin
      },
      ready:function () {
        this.$watch('editFormData',function () {
          this.init();
        });
      },
      data:function () {
        return{
          showSpin:false,
          column:1,
          isClose:false,
          positionDrop:{},
          positionDropData:[],
          treeData:{},
          datePicker: {
            value: '',
            options: {
              format: 'YYYY/MM/DD',
              monthList: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
              weekList: ['一', '二', '三', '四', '五', '六', '日']
            }
          }
        }
      },
      vuex:{
        actions:{
          getKeyValueData,
          insert,
          update,
          getLocationByOrganization,
          getPositionByOrganization,
          getSupervisorByPosition
        }
      },
      methods: {
        init:function () {
          var t = this;
          this.$nextTick(function () {
            this.initEditTree();
            this.initWidth();
            this.initForm();
          });
        },
        //初始化表单里面的树
        initEditTree:function () {
          var t = this;
          var $editTree = $(t.$el).find('.dayhr_drop_select');
          var len = $editTree.length;

          for(var i=0;i<len;i++){
            var param = JSON.parse($editTree.eq(i).attr('data-keyValue'));
            var id = 'id' + new Date().getTime() + parseInt(Math.random(1000)*1000);
            $editTree.eq(i).prop('id',id);
            var name = $editTree.eq(i).attr('data-name');
            var value = $editTree.eq(i).attr('data-value');
            var title = $editTree.eq(i).attr('data-title');
            var isReadOnly = $editTree.eq(i).attr('data-readonly');
            this.getKeyValueData(param,function (data,extraObj) {

            var drop = new dayhrDropSelect({
                id:extraObj.id,
                width:168,
                maxHeight:250,
                placeholder:"select " + extraObj.title,
                data:data,
                name:extraObj.name,
                onSelected:function(oSelect, type){
                 //点击组织带work location
                  if(t.formInfoSetId == 'comp_person_list'){
                      if(extraObj.name == 'org_id'){
                         t.getLocationByOrganization({customParam:{org_id:oSelect.value}},function(data){
                            var workLocation = data.maps[0].work_location;
                            $(t.$el).find('input[name="work_location"]').val(workLocation);
                         });
                      }
                  }

                  //点击组织带出职位和work location ,点击职位带出上级人
                  if(t.formInfoSetId == 'comp_person_base_office'){
                      if(extraObj.name == 'org_id'){
                         t.getLocationByOrganization({customParam:{org_id:oSelect.value}},function(data){
                            var workLocation = data.maps[0].work_location;
                            $(t.$el).find('input[name="work_location"]').val(workLocation);
                         });
                          t.getPositionByOrganization({customParam:{org_id:oSelect.value}},function(data){

                         });
                        var data = t.positionDropData;
                        var childrenData = t.getTreeData(data);
                        var positionTreeData = childrenData[oSelect.node.name];
                         t.positionDrop.updateTreeJson(positionTreeData);

                      }
                      if(extraObj.name == 'pos_id'){
                         t.getSupervisorByPosition({customParam:{pos_id:oSelect.value}},function(data){
                           if(data.maps.length&&data.maps[0]&&data.maps[0].first_name){
                            var supervisor = data.maps[0].first_name;
                            $(t.$el).find('input[name="supervisor"]').val(supervisor);
                           }
                         });
                      }

                  }
                }
              });
              if(name = 'pos_id'){
                 t.positionDropData = data;
                 t.positionDrop = drop;
              }

              drop.setValue(extraObj.value);
              if(extraObj.isReadOnly == 'true'){
                drop.setDisabled(true);
              }

            },null,{id:id,name:name,value:value,title:title,isReadOnly:isReadOnly})
          }
        },
        getTreeData:function(data){
          var t = this;
          var obj = t.treeData;
          for(var i = 0;i<data.length;i++){
          if(data[i].children){
            t.getTreeData(data[i].children);
              obj[data[i].name] = data[i].children;
            }else{
              obj[data[i].name] = [];
            }
          }
          return obj;
        },
        initWidth:function () {
          var data = this.editFormData.columnEdit;
          var len = data.filter(function (value) {
            return value.isEditShow
          }).length;
          this.column = len>15?2:1;
        },
        //清空 form
        clearForm:function(){
          var editFormDataBack = JSON.parse(JSON.stringify(this.editFormData));
          this.editFormData = null;
          this.editFormData = editFormDataBack;
        },
        initForm:function () {
          var t = this;
          var formRules = t.setFormRule();
          $(t.$el).find("#editForm").validator({
              theme: "yellow_right",
              timely: 0, // 保存的时候验证
              focusCleanup: true, //聚焦时清除错误提示
              stopOnError: true,
              //待验证字段集合
              rules:formRules.oRules,
              fields: formRules.validatorFields,
              valid: function (form) {
                var formValue = t.getFormValue($(t.$el).find("#editForm").serializeArray());

                //add提交表单
                if( t.formType == 'add'){
                  if(t.formEditExtraData.editCondition){
                    formValue.push(t.formEditExtraData.editCondition);
                  }
                   var param = {
                      infoSetId:t.formInfoSetId,
                      dataList:formValue,
                   }
                   t.insert(param,function () {
                      t.formSubmitFun();
                      t.$Notification.success('add Success','', 2000);
                      t.clearForm();
                      t.formSubmitFun();
                      if(t.isClose){
                       t.formCancelFun();
                      }
                    },function (data) {
                      t.$Notification.warning(data,'', 2000);
                    });
                }
                //update 提交表单

                if( t.formType == 'update'){
                   var param = {
                      infoSetId:t.formInfoSetId,
                      dataList:formValue,
                      uuid:t.editFormData.data.uuid
                   }
                   t.update(param,function () {
                      t.clearForm();
                      t.formSubmitFun();
                      t.$Notification.success('update Success','', 2000);
                      t.formCancelFun();
                    },function (data) {
                      t.$Notification.warning(data,'', 2000);
                    });
                }
              }
          });
        },
        setFormRule:function(){
          var t = this;
          var columnEdit = t.editFormData.columnEdit;
          var oRules={},validatorFields={};
          for(var i =0;i<columnEdit.length;i++){
              var item = columnEdit[i];
              if(item.isMust){
                  validatorFields[item.name] = {
                      rule: 'required;',
                      msg: {
                          required:"This field is required"
                      }
                  };
              }
              if(item.regExpress){
                  var _reg = new RegExp(item.regExpress);
                  oRules[item.name] = [_reg, 'The format is not correct'];
                  if(validatorFields[item.name]){
                      validatorFields[item.name].rule += " "+item.name+";";
                  }else{
                      validatorFields[item.name] = {
                          rule:item.name+";"
                      };
                  }
              }
              if(item.cellType == 'email'){
                  oRules['email'] = [_reg, 'The email Format is not correct'];
                  if(validatorFields[item.name]){
                      validatorFields[item.name].rule += "email+;";
                  }else{
                      validatorFields[item.name] = {
                          rule:"email;"
                      };
                  }
              }
          }
          return {oRules:oRules,validatorFields:validatorFields}
        },
        getFormValue:function(data){
          var t = this;
          var paramValue=[];
          var len = data.length;
          for (var i=0;i<len;i++){
            if(data[i].value){
              if(t.formType == 'update' &&data[i].value != t.editFormData.data[data[i].name]){
                  paramValue.push({key:data[i].name,value:data[i].value});
              }else if(t.formType == 'add'){
                paramValue.push({key:data[i].name,value:data[i].value});
              }

            }
          }
          console.log(paramValue);
          return paramValue;
        }
      },
      props:{
        editFormData:{
          type:Object,
        },
        formType:{
          type:String,
        },
        formInfoSetId:{
          type:String,
        },
        formCancelFun:{
          type:Function
        },
        formSubmitFun:{
          type:Function
        },
        formEditExtraData:{
          type:Object
        }
      }
    }
</script>
<style rel="stylesheet/scss" type="text/css" lang="scss" scoped>
  @import "../../assets/css/variable";
  .form {
    padding: 20px;
    margin: 0 auto;
    min-height: 150px;
    .msg-wrap{
      position: fixed;
      margin-top:6px;
    }
    .input_line{
      /*height: 40px;*/
      line-height: 38px;
      float: left;
      .input_line_left{
        width: 160px;
        text-align: right;
        float: left;
        padding: 0 10px;
        .label{
          text-align: right;
          padding-right: 20px;
          position: relative;
          display: inline-block;
          width: 100%;
          box-sizing: border-box;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
          vertical-align: middle;
          font-weight: bold;
          &.isMust:after{
            content: '*';
            color: #ff5500;
            position: absolute;
            right: 2px;
            top: 6px;
            font-size: 22px;
          }
        }
      }
      .input_line_right{
        width: 200px;
        text-align: left;
        float: left;
        .input{
          width: 170px;
          box-sizing: border-box;
          padding: 0 12px;
          color: #666;
        }
        .textarea{
          width: 170px;
          height: 60px;
        }
      }
    }
    .btn_group{
      margin-top: 40px;
      button{
        margin: 0 12px;
      }
      text-align: center;
    }
  }
</style>
